const Service = require('egg').Service

class CourseCategoryService extends Service {
  async index() {
    const { ctx, app } = this
    // 获取当前分类
    const curCategory = await ctx.find('CourseCategory', {}, 'findAll')
    const tmp = []
    if (curCategory.length > 0) {
      curCategory.forEach(item => {
        tmp.push(item.dataValues.categoryId)
      })
    }
    const courseRes = await ctx.service.moocCourse.index({ pageNo: 1, pageSize: 30 })
    const records = courseRes.records
    // 请求接口
    const courseCategoryUrl = `${app.config.moocDomain}/web/j/channelBean.listMocChannelCategoryRel.rpc?csrfKey=${app.config.moocCookie.NTESSTUDYSI}`
    let count = 0
    for (let i = 0, len = records.length; i < len; i++) {
      const categoryRes = await ctx.helper.curlPost(courseCategoryUrl, {
        channelId: records[i].channelId
      })
      if (categoryRes.data.code === 0) {
        const postData = []
        categoryRes.data.result.forEach(item => {
          if (!tmp.includes(records[i].channelId)) {
            const dict = {
              channelId: records[i].channelId,
              categoryId: item.id,
              categoryName: item.name
            }
            postData.push(dict)
          }
        })
        await ctx.bulkCreate('CourseCategory', postData)
        count += 1
      } else {
        break
      }
    }
    return count
  }
}

module.exports = CourseCategoryService
